var express = require('express');
var router = express.Router();
const bcrypt = require("bcrypt");
const { TOKEN_KEY } = require('../utils/const');
const jwt = require("jsonwebtoken");

const { register, checkUsername, login, getLessors, getState ,getLessorsOrders} = require('../service/lessorsService')

// router.get('/', function(req, res, next) {
//   res.render('index', { title: 'Express' });
// });

router.post('/register', async function (req, res, next) {
    var { username, password, phone } = req.body
    password = bcrypt.hashSync(password, 10)
    const data = await register({ username, password, phone })
    res.send(data)
})

router.post('/checkUsername', async function (req, res, next) {
    const data = await checkUsername(req.body)
    res.send(data)
})

router.post('/login', async function (req, res, next) {
    console.log(req.body);
    var { username, password } = req.body;
    const data = await login( {username} )
    if(data.length==0){
        res.send({
            status: 0,
            message: "登录失败"
        })
    }
    if (bcrypt.compareSync(password, data[0].password)) {
        const token = jwt.sign(
            { username, _id: data[0]._id },
            TOKEN_KEY,
            { expiresIn: 6000 }
        )
        if(data[0].state==2){
            res.send({
                status: 0,
                message: "登录失败,该账号已被冻结"
            })
        }
        res.send({
            ...data,
            token,
            status: 1
        })
    } else {
        res.send({
            status: 0,
            message: "登录失败"
        })
    }
    
})
//查看出租方的订单
router.post('/getLessorsOrders',async function(req,res,next){
     const  lessorsId=req.body
     const data =await getLessorsOrders(lessorsId)
     res.send(data)
})

router.get('/isLogin', async function (req, res, next) {
    const token = req.query;
    const { username } = jwt.verify(token[0], TOKEN_KEY);
    res.send({
        status: 1,
        message: '成功',
        username
    })
})

//审核出租渲染列表
router.get('/getLessors', async function (req, res, next) {
    const data = await getLessors(req.query)
    res.send(data)
})

//
router.get('/getState', async function (req, res, next) {
    const data = await getState(req.query)
    res.send(data)
})

module.exports = router;